<?php
require $_SERVER['DOCUMENT_ROOT'].'/../_core/common.php';

$db = new DB('news');

$id = isset($_POST['id']) ? intval($_POST['id']) : 0;
$news = isset($_POST['news']) ? intval($_POST['news']) : 1;

if($id<0){
	exit;
}

//根据id查找所有父级数据数组
function parent_check($db,$id){
	global $category_arr;
	$sql = 'select id,title,parent_id from categories where id='.$id.' limit 1';
	$data = $db->query($sql)->getOne();
	
	array_push($category_arr, $data);
	
	if($data['parent_id']!=0){
		parent_check($db,$data['parent_id']);
	}

}

//提取数组的id
function id_get($array){
	foreach($array as $arr){
		$id_arr[] = $arr['id'];
	}
	return $id_arr;
}

//返回html代码
function category_lists($db,$id,$id_arr,$news=1){
	$string = '<select id="category_'.$id.'">';
	
	$category_sql = 'select id,title from categories where parent_id='.$id.' and is_del=1';
	$category_rs = $db->query($category_sql)->getAll();
	
	if($news==2 && $id==0){
		//来自新闻内容页的顶级栏目
		$string .= '<option>请选择栏目</option>';
	}elseif($id==0){
		$string .= '<option value ="0">整站</option>';
	}else{
		$string .= '<option value ="'.$id.'">当前</option>';
	}
	
	foreach($category_rs as $data){
		if(in_array($data['id'],$id_arr)){
			$string .= '<option value ="'.$data['id'].'" selected="selected">'.$data['title'].'</option>';
		}else{
			$string .= '<option value ="'.$data['id'].'">'.$data['title'].'</option>';
		}
	}
	
	$string .= '</select>';
	
	return $string;
}

if($id==0){
	$html = '<select id="category_0">';
	
	$category_sql = 'select id,title from categories where parent_id=0 and top_id=0 and is_del=1';
	$category_rs = $db->query($category_sql)->getAll();
	
	if($news!=2){//不是来自新闻内容页
		$html .= '<option value ="0">整站</option>';
	}else{
		$html .= '<option>请选择栏目</option>';
	}
	
	foreach($category_rs as $data){
		$html .= '<option value ="'.$data['id'].'">'.$data['title'].'</option>';
	}
}else{
	$category_arr = array();
	parent_check($db,$id);

	$id_arr = id_get($category_arr);

	array_push($id_arr, '0');//加顶级栏目的父id=0
	$id_arr = array_reverse($id_arr);//逆向排序

	$html = '';
	foreach($id_arr as $id){
		$html .= category_lists($db,$id,$id_arr,$news);
	}
}

echo $html;
exit;